﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using com.lover.astd.common.model;
using com.lover.astd.common.model.enumer;

namespace com.lover.astd.common.config
{
    public class GlobalConfig
    {
        private static GlobalConfig _instance;
        public static GlobalConfig getInstance()
        {
            if (_instance == null) _instance = new GlobalConfig();
            return _instance;
        }
        public static string Version = "傲视天地小助手v0.6385";
        private string _confFilePath = "account.ini";
        private List<AccountData> _accountAll = new List<AccountData>();
        private bool _isDebug = false;
        private AccountData _lastLoginAccount;
        /// <summary>
        /// 是否是调试模式
        /// </summary>
        public bool IsDebug{ get { return _isDebug; } }
        public GlobalConfig() 
        {
#if DEBUG
            _isDebug = true;
#endif
        }
        public void addAccount(AccountData acc)
        {
            if (acc.Server_type == ServerType.Custom)
            {
                // 直接替换custom, custom只保持一个
                for (int i = 0; i < _accountAll.Count; i++)
                {
                    if (_accountAll[i].Server_type == ServerType.Custom)
                    {
                        _accountAll.RemoveAt(i); i--;
                    }
                }
            }
            _accountAll.Add(acc);
            setLastLoginAccount(acc);
        }
        public void removeAccount(AccountData acc)
        {
            _accountAll.Remove(acc);
            saveSettings();
        }
        public List<AccountData> getAllAccounts()
        {
            return _accountAll;
        }
        public void setLastLoginAccount(AccountData acc)
        {
            foreach (AccountData tmpacc in _accountAll)
            {
                if (acc.Server_type == ServerType.Custom)
                {
                    if (tmpacc.Server_type == ServerType.Custom) tmpacc.IsLastLogin = true;
                    else tmpacc.IsLastLogin = false;
                }
                else
                {
                    if (tmpacc.Equals(acc)) tmpacc.IsLastLogin = true;
                    else tmpacc.IsLastLogin = false;
                }
            }
            _lastLoginAccount = acc;
            saveSettings();
        }
        public AccountData getLastLoginAccount()
        {
            if (_lastLoginAccount != null) return _lastLoginAccount;
            if (_accountAll.Count == 0) return null;
            _lastLoginAccount = _accountAll[0];
            return _lastLoginAccount;
        }
        public Dictionary<ServerType, List<AccountData>> getAllAccountByType()
        {
            Dictionary<ServerType, List<AccountData>> accounts = new Dictionary<ServerType, List<AccountData>>();
            foreach (ServerType tp in Enum.GetValues(typeof(ServerType)))
            {
                List<AccountData> dts = new List<AccountData>();
                foreach (AccountData tmpdt in _accountAll)
                {
                    if (tmpdt.Server_type == tp) dts.Add(tmpdt);
                }
                accounts.Add(tp, dts);
            }
            return accounts;
        }
        public void delAccount(AccountData acc)
        {
            bool done = false;
            for (int i = 0, len = _accountAll.Count; i < len; i++)
            {
                AccountData tmp = _accountAll[i];
                if (acc.Equals(tmp))
                {
                    _accountAll.RemoveAt(i);
                    done = true;
                    break;
                }
            }
            if (done) saveSettings();
        }
        public bool loadSettings()
        {
            FileInfo finfo = new FileInfo(_confFilePath);
            if (!finfo.Exists)
            {
                return false;
            }
            _accountAll.Clear();
            StreamReader fr = finfo.OpenText();
            string[] spliters = new string[] { "=" };
            string key = null, value = null;
            string line = fr.ReadLine();
            while (line != null)
            {
                line = line.Trim();
                if (line.Length > 0 && !line.StartsWith("#"))
                {
                    int squot_index = line.IndexOf('=');
                    if (squot_index < 0) continue;
                    key = line.Substring(0, squot_index);
                    value = line.Substring(squot_index + 1);
                    if (key != null && value != null && key.Length > 0 && value.Length > 0)
                    {
                        handleConfigPair(key, value);
                    }
                }
                line = fr.ReadLine();
            }
            fr.Close();
            return true;
        }
        private void handleConfigPair(string key, string value)
        {
            if (!key.ToLower().Equals("account")) return;
            
            string[] account_subs = value.Split(':');
            // server_type:server_id:username:password(b64):is_lastlogin(0|1):customLoginUrl:customGameUrl
            if (account_subs.Length < 7) return;
            string server_type = account_subs[0], server_idstr = account_subs[1];
            string username = account_subs[2], pass_b64 = account_subs[3];
            bool islastlogin = account_subs[4] == "1";
            string customLoginUrl = account_subs[5], customGameUrl = account_subs[6];
            if(customLoginUrl.Length > 0) customLoginUrl = customLoginUrl.Replace('*', ':');
            if (customGameUrl.Length > 0) customGameUrl = customGameUrl.Replace('*', ':');
            int server_id = 0;
            Int32.TryParse(server_idstr, out server_id);
            string roleName = "";
            if (account_subs.Length >= 8) roleName = account_subs[7];
            AccountData dt = new AccountData();
            dt.setServerType(server_type);
            dt.ServerId = server_id;
            dt.UserName = username;
            dt.Password = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(pass_b64));
            dt.RoleName = roleName;
            dt.CustomLoginUrl = customLoginUrl;
            dt.CustomGameUrl = customGameUrl;
            dt.IsLastLogin = islastlogin;
            if (dt.IsLastLogin) _lastLoginAccount = dt;
            _accountAll.Add(dt);
        }
        public void saveSettings()
        {
            FileInfo finfo = new FileInfo(_confFilePath);
            FileStream stream = null;
            if (!finfo.Exists)
            {
                stream = finfo.Create();
            }
            else stream = finfo.Open(FileMode.Truncate, FileAccess.Write);
            StreamWriter wr = new StreamWriter(stream);
            wr.WriteLine("# astd account ini file, please donnot change this file by yourself");

            foreach (AccountData dt in _accountAll)
            {
                byte[] bytes = UTF8Encoding.UTF8.GetBytes(dt.Password);
                string pass_b64 = Convert.ToBase64String(bytes);
                string line = String.Format("account={0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}",
                    dt.Server_type.ToString(), dt.ServerId, dt.UserName, pass_b64, dt.IsLastLogin ? 1 : 0,
                    dt.CustomLoginUrl.Replace(':', '*'), dt.CustomGameUrl.Replace(':', '*'), dt.RoleName);
                wr.WriteLine(line);
            }

            wr.Close();
            stream.Close();
        }
    }
}
